/*
 * @Description: 
 * @version: 
 * @Author: Eve
 * @Date: 2019-09-21 16:42:04
 * @LastEditors: Eve
 * @LastEditTime: 2019-09-21 17:55:59
 */
// 中介模式简单实现

let mediator = (function() {
	// 储存可被广播或监听的topic
	let topics = {}

	// 订阅一个topic 提供一个回调函数 一旦topic被广播就执行回调
	let subscribe = function(topic, fn) {
		if (!topics[topic]) {
			topics[topic] = []
		}

		topics[topic].push({ context: this, callback: fn })
		return this
	}

	// 发布/广播事件到程序的剩余部分
	let publish = function(topic) {
		let args
		if (!topics[topic]) {
			return false
		}

		// args = Array.prototype.slice.apply(arguments, [1])
		args = Array.prototype.slice.call(arguments, 1)
		for (let i = 0, l = topics[topic].length; i < l; i++) {
			let subscription = topics[topic][i]
			subscription.callback.apply(subscription.context, args)
		}
		return this
	}

	return {
		Publish: publish,
		Subscribe: subscribe,
		installTo: function(obj) {
			obj.subscribe = subscribe
			obj.publish = publish
		}
	}
})()
